package com.kun.kunkunmall.order.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class MyMQConfig {

    /**
     * 订单服务队列
     *
     * @return
     */
    @Bean("orderDelayQueue")
    public Queue orderDelayQueue() {
        HashMap<String, Object> arguments = new HashMap<>();
        return QueueBuilder
                .durable("order.delay.queue").ttl(60000)
                .withArguments(arguments).deadLetterExchange("order-event-exchange")
                .deadLetterRoutingKey("order.release.order").build();
    }

    /**
     * 订单服务的死信队列
     *
     * @return
     */
    @Bean("orderReleaseOrderQueue")
    public Queue orderReleaseOrderQueue() {
        return QueueBuilder.durable("order.release.order.queue").build();
    }


    /**
     * 秒杀订单的队列
     *
     * @return
     */
    @Bean("orderSeckillOrderQueue")
    public Queue orderSeckillOrderQueue() {
        return QueueBuilder.durable("order.seckill.order.queue").build();
    }


    /**
     * 订单服务的交换机
     *
     * @return
     */
    @Bean("orderEventExchange")
    public Exchange orderEventExchange() {
        return ExchangeBuilder.topicExchange("order-event-exchange").durable(true).build();
    }

    /**
     * 创建订单时队列和交换机的绑定关系
     *
     * @param queue
     * @param exchange
     * @return
     */
    @Bean
    public Binding orderCreateOrderBinding(@Qualifier("orderDelayQueue") Queue queue, @Qualifier("orderEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("order.create.order").noargs();
    }

    /**
     * 延迟队列和交换机的绑定关系
     *
     * @return
     */
    @Bean
    public Binding orderReleaseOrderBinding(@Qualifier("orderReleaseOrderQueue") Queue queue, @Qualifier("orderEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("order.release.order").noargs();
    }

    /**
     * 订单释放和库存释放直接绑定
     */
    @Bean
    public Binding orderReleaseOtherBinding() {
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "order-event-exchange",
                "order.release.other.#",
                null);
    }


    @Bean
    public Binding orderSeckillOrderQueueBinding(@Qualifier("orderSeckillOrderQueue") Queue queue, @Qualifier("orderEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("order.seckill.order").noargs();
    }

}
